package org.adorsys.aderp.orga.service;

import java.util.List;

import org.adorsys.aderp.orga.domain.OrgaAddressRole;
import org.adorsys.aderp.orga.domain.OrgaResource;
import org.adorsys.aderp.orga.domain.ResourceAddress;
import org.adorsys.aderp.orga.repository.ResourceAddressRepository;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.PageRequest;


public class ResourceAddressServiceImpl implements ResourceAddressService {
	
		   
	@Override
	public List<ResourceAddress> findByOrgaResource(OrgaResource orgaResource){
		return resourceAddressRepository.findByOrgaResource(orgaResource);
	}
    
    public void saveResourceAddress(ResourceAddress resourceAddress) {
    	OrgaResource orgaResource = resourceAddress.getOrgaResource();
    	if(StringUtils.isBlank(resourceAddress.getResourceAddressKey())){
    		 OrgaAddressRole addressRole = resourceAddress.getAddressRole();
    		 resourceAddress.setResourceAddressKey(orgaResource.getResourceKey() +":"+addressRole.getAddressRoleKey() +":"+RandomStringUtils.randomNumeric(3));
    	}
    	// this is a dependent object of the OrgaResource. So same record owner.
    	if(StringUtils.isBlank(resourceAddress.getRecordOwner())){
    		resourceAddress.setRecordOwner(orgaResource.getRecordOwner());
    	}
    	resourceAddressRepository.save(resourceAddress);
    }


    @Override
    public  Page<ResourceAddress> searchResourceAddress(OrgaResource orgaResource,OrgaAddressRole addressRole, Integer page, Integer size)
    {
		PageRequest pageable = new PageRequest(page, size);
		if(orgaResource!=null && addressRole==null){
			return resourceAddressRepository.findByOrgaResource(orgaResource, pageable);
		} else if(orgaResource!=null && addressRole!=null){
			return resourceAddressRepository.findByOrgaResourceAndAddressRole(orgaResource, addressRole, pageable);
		} else if(orgaResource==null && addressRole!=null){
			return resourceAddressRepository.findByAddressRole(addressRole, pageable);
		} else {
			return resourceAddressRepository.findAll(pageable);
		}
    }
}
